#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import sys
import string
import simplejson
import MySQLdb
import time
from Tools import getPid
from Tools import connectMySQL

def help():
    print '''
[usage]
  python accuTotal.py
[help]
  python accuTotal.py help
    '''

def ISOString2Time(s):
    '''
    convert a ISO format time to second
    from:2006-04-12 16:46:40 to:23123123
    '''
    return time.mktime(time.strptime(s, '%Y%m%d %X'))

def ISOString2Time_2(s):
    '''
    convert a ISO format time to second
    from:2006-04-12 16:46:40 to:23123123
    '''
    return time.mktime(time.strptime(s, '%Y-%m-%d %X'))

def accuTotal(tableName, json, datetime):
    mysqldb = connectMySQL.connMySQL_stat()
    mysqldb2 = connectMySQL.connMySQL("guid")
    lasttime = ' 23:59:59'
    time2 = ISOString2Time(datetime + lasttime)
    day2 = datetime
    jsonVal = simplejson.loads(json)
    jsonValRes = jsonVal["results"]
    count = 0

    for result in jsonValRes:
        cursor=mysqldb2.cursor()
        SQL = "SELECT count(*) FROM clientUser where `pid` = \"%s\" and `regtime` <= \"%s\"" % (result, time2)
        cursor.execute(SQL)
        resultSet=cursor.fetchall()
        count = resultSet[0][0]
        #print SQL

        try:
            cursor=mysqldb.cursor()
            SQL = "SELECT `pid` FROM `%s` WHERE `pid` = \"%s\"" % (tableName, result)
            cursor.execute(SQL)
            resultSet=cursor.fetchall()
            i = 0
            for res in resultSet:
                i+=1
            if (i == 0):
                SQL = "INSERT INTO `%s` (pid, date, pv, uv, vv, register, upload, newuser, alluser, ver)\
 VALUES (\"%s\", \"%s\", 0, 0, 0, 0, 0, 0, %d, 0)" % (tableName, result, day2, count)
                #print SQL
                cursor.execute(SQL)
            else:
                SQL = "UPDATE `%s` SET `alluser` = %d where `pid` = \"%s\" and `date` = \"%s\"" % (tableName, count, result, day2)
                #print SQL
                cursor.execute(SQL)
        except MySQLdb.Error, e:
            print e
            resultStr='failed 4001'
            print resultStr
            return resultStr

def main(date):
    if len(sys.argv[1]) == 4:
        help()
        exit(1)
    ISOTIMEFORMAT='%Y-%m-%d %X'
    btimeStr = time.strftime(ISOTIMEFORMAT, time.localtime())
    btime = ISOString2Time_2(btimeStr)
    print "%s Starting..." % btimeStr
    json = getPid.getMainPid_json()
    accuTotal("stat_day_main", json, date)
    json = getPid.getPaikePid_json()
    accuTotal("stat_day_paike", json, date)
    json = getPid.getChannelPid_json()
    accuTotal("stat_day_channel", json, date)
    json = getPid.getFactoryPid_json()
    accuTotal("stat_day_factory", json, date)
    etimeStr = time.strftime(ISOTIMEFORMAT, time.localtime())
    etime = ISOString2Time_2(etimeStr)
    print "%s End" % etimeStr
    print "Take Time: %ds" % (etime-btime)

if __name__ == '__main__':
    main(sys.argv[1])


